// @ts-check
// 加载环境变量配置（必须在其他导入之前）
import { config } from 'dotenv';
import { resolve, dirname } from 'path';
import { fileURLToPath } from 'url';

// 获取当前文件的目录路径
const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);

// 使用绝对路径加载.env文件
const envPath = resolve(__dirname, '../.env');
console.log('🔧 加载环境变量文件:', envPath);

// 检查文件是否存在
import { existsSync } from 'fs';
if (!existsSync(envPath)) {
  console.error('❌ .env文件不存在:', envPath);
} else {
  console.log('✅ .env文件存在');
}

const result = config({ path: envPath });

if (result.error) {
  console.error('❌ 环境变量加载失败:', result.error);
} else {
  console.log('✅ 环境变量加载成功');
  console.log('🔍 环境变量详情:');
  console.log('- SHOPIFY_API_KEY:', process.env.SHOPIFY_API_KEY || '❌ 未设置');
  console.log('- HOST:', process.env.HOST || '❌ 未设置');
  console.log('- SHOPIFY_API_SECRET:', process.env.SHOPIFY_API_SECRET ? '✅ 已设置' : '❌ 未设置');
  console.log('- PORT:', process.env.PORT || '❌ 未设置');
  console.log('- NODE_ENV:', process.env.NODE_ENV || '❌ 未设置');
  
  // 显示所有以SHOPIFY_开头的环境变量
  console.log('🎯 所有SHOPIFY相关环境变量:');
  Object.keys(process.env).filter(key => key.startsWith('SHOPIFY_')).forEach(key => {
    console.log(`- ${key}:`, process.env[key] ? '✅ 已设置' : '❌ 未设置');
  });
}

// 导入Node.js核心模块
import { join } from "path";
import { readFileSync } from "fs";
// 导入Express框架
import express from "express";
import serveStatic from "serve-static";

// 导入Shopify应用配置
import shopify from "./shopify.js";
// 导入产品创建功能
import productCreator from "./product-creator.js";
// 导入隐私相关的Webhook处理器
import PrivacyWebhookHandlers from "./privacy.js";

// 配置服务器端口，优先级：BACKEND_PORT > PORT > 3000
const PORT = parseInt(
  process.env.BACKEND_PORT || process.env.PORT || "8080",
  10
);

// 根据环境配置静态文件路径
// 生产环境：使用构建后的dist目录
// 开发环境：使用frontend源代码目录
const STATIC_PATH =
  process.env.NODE_ENV === "production"
    ? `${process.cwd()}/frontend/dist`
    : `${process.cwd()}/frontend/`;

// 创建Express应用实例
const app = express();

// ===========================================
// Shopify认证和Webhook处理设置
// ===========================================

// 设置OAuth认证开始路由，增强日志记录
app.get(shopify.config.auth.path, async (req, res, next) => {
  console.log('\n🚀 OAuth认证开始');
  console.log('=====================================');
  console.log('📋 认证请求信息:');
  console.log('- URL:', req.url);
  console.log('- Query参数:', JSON.stringify(req.query, null, 2));
  console.log('- Shop参数:', req.query.shop || '❌ 缺失');
  console.log('- User Agent:', req.headers['user-agent']);
  console.log('- 请求时间:', new Date().toISOString());
  
  if (!req.query.shop) {
    console.log('❌ 错误: OAuth开始时缺少shop参数');
    return res.status(400).json({
      error: 'Missing shop parameter',
      message: '请提供shop参数，格式: ?shop=your-store.myshopify.com',
      example: `${req.protocol}://${req.get('host')}${req.path}?shop=your-store.myshopify.com`
    });
  }
  
  console.log('✅ 参数验证通过，开始OAuth流程...');
  next();
}, shopify.auth.begin());

// 添加调试信息
console.log('🔍 Shopify应用配置信息:');
console.log('- API Key:', process.env.SHOPIFY_API_KEY);
console.log('- Host:', process.env.HOST);
console.log('- 认证路径:', shopify.config.auth.path);
console.log('- 回调路径:', shopify.config.auth.callbackPath);
console.log('- 完整回调URL:', `https://${process.env.HOST}${shopify.config.auth.callbackPath}`);

// 设置OAuth认证回调路由，增强错误处理和日志记录
app.get(
  shopify.config.auth.callbackPath,
  async (req, res, next) => {
    console.log('\n🔄 OAuth回调处理开始');
    console.log('=====================================');
    console.log('📋 请求信息:');
    console.log('- URL:', req.url);
    console.log('- Method:', req.method);
    console.log('- Query参数:', JSON.stringify(req.query, null, 2));
    console.log('- Headers:', JSON.stringify({
      'user-agent': req.headers['user-agent'],
      'referer': req.headers.referer,
      'host': req.headers.host
    }, null, 2));
    
    // 验证必要参数
    const { shop, code, state, hmac } = req.query;
    console.log('\n🔍 OAuth参数验证:');
    console.log('- Shop:', shop || '❌ 缺失');
    console.log('- Code:', code ? '✅ 存在' : '❌ 缺失');
    console.log('- State:', state ? '✅ 存在' : '❌ 缺失');
    console.log('- HMAC:', hmac ? '✅ 存在' : '❌ 缺失');
    
    if (!shop) {
      console.log('❌ 错误: 缺少shop参数');
      return res.status(400).json({
        error: 'Missing shop parameter',
        message: '缺少必要的shop参数',
        received_params: req.query
      });
    }
    
    if (!code) {
      console.log('❌ 错误: 缺少authorization code');
      return res.status(400).json({
        error: 'Missing authorization code',
        message: '缺少授权码，可能是用户拒绝了授权',
        shop: shop
      });
    }
    
    next();
  },
  shopify.auth.callback(),
  async (req, res, next) => {
    console.log('\n✅ OAuth回调处理成功');
    console.log('=====================================');
    
    // 获取会话信息
    const session = res.locals.shopify?.session;
    if (session) {
      console.log('📊 会话信息:');
      console.log('- Session ID:', session.id);
      console.log('- Shop:', session.shop);
      console.log('- 访问令牌:', session.accessToken ? '✅ 已获取' : '❌ 未获取');
      console.log('- 令牌范围:', session.scope);
      console.log('- 在线状态:', session.isOnline ? '在线' : '离线');
      console.log('- 过期时间:', session.expires || '永不过期');
      
      // 记录访问令牌信息（仅显示前几位用于调试）
      if (session.accessToken) {
        console.log('- 访问令牌预览:', session.accessToken.substring(0, 10) + '...');
      }
      
      console.log('\n🎯 授权成功详情:');
      console.log('- 商店域名:', session.shop);
      console.log('- API版本:', process.env.SHOPIFY_API_VERSION);
      console.log('- 授权范围:', session.scope);
      console.log('- 授权时间:', new Date().toISOString());
    } else {
      console.log('⚠️  警告: 未找到会话信息');
    }
    
    next();
  },
  (err, req, res, next) => {
    console.log('\n❌ OAuth回调错误处理');
    console.log('=====================================');
    console.log('错误详情:', {
      message: err.message,
      stack: err.stack,
      query: req.query,
      shop: req.query.shop
    });
    
    // 根据错误类型返回不同的响应
    if (err.message.includes('Invalid state')) {
      return res.status(400).json({
        error: 'Invalid state parameter',
        message: 'State参数无效，可能存在CSRF攻击或会话过期',
        shop: req.query.shop
      });
    }
    
    if (err.message.includes('Invalid HMAC')) {
      return res.status(400).json({
        error: 'Invalid HMAC signature',
        message: 'HMAC签名验证失败，请求可能被篡改',
        shop: req.query.shop
      });
    }
    
    // 通用错误处理
    res.status(500).json({
      error: 'OAuth callback failed',
      message: err.message,
      shop: req.query.shop,
      timestamp: new Date().toISOString()
    });
  },
  shopify.redirectToShopifyOrAppRoot()
);

// 设置Webhook处理路由，用于接收Shopify发送的事件通知
app.post(
  shopify.config.webhooks.path,
  shopify.processWebhooks({ webhookHandlers: PrivacyWebhookHandlers })
);

// 如果您要在/api路径之外添加路由，请记住
// 也要在web/frontend/vite.config.js中为它们添加代理规则

// ===========================================
// API路由中间件配置
// ===========================================

// 对所有/api/*路径启用Shopify会话验证中间件（排除认证相关路径）
app.use("/api/*", (req, res, next) => {
  // 跳过认证和回调路径的会话验证
  if (req.path.startsWith('/api/auth')) {
    return next();
  }
  
  console.log('\n🔐 会话验证检查');
  console.log('=====================================');
  console.log('- 请求路径:', req.path);
  console.log('- 请求时间:', new Date().toISOString());
  
  // 应用会话验证中间件
  return shopify.validateAuthenticatedSession()(req, res, (err) => {
    if (err) {
      console.log('❌ 会话验证失败:', err.message);
      console.log('- 错误类型:', err.constructor.name);
      console.log('- 会话状态:', res.locals.shopify?.session ? '存在' : '不存在');
    } else {
      console.log('✅ 会话验证成功');
      if (res.locals.shopify?.session) {
        console.log('- 商店:', res.locals.shopify.session.shop);
        console.log('- 会话ID:', res.locals.shopify.session.id);
      }
    }
    next(err);
  });
});

// 启用JSON解析中间件
app.use(express.json());

// ===========================================
// API端点定义
// ===========================================

// GET /api/products/count - 获取商店产品总数
app.get("/api/products/count", async (_req, res) => {
  // 创建GraphQL客户端，使用当前会话
  const client = new shopify.api.clients.Graphql({
    session: res.locals.shopify.session,
  });

  // 执行GraphQL查询获取产品总数
  const countData = await client.request(`
    query shopifyProductCount {
      productsCount {
        count
      }
    }
  `);

  // 返回产品总数
  res.status(200).send({ count: countData.data.productsCount.count });
});

// POST /api/products - 创建示例产品
app.post("/api/products", async (_req, res) => {
  let status = 200;
  let error = null;

  try {
    // 调用产品创建器，使用当前会话创建示例产品
    await productCreator(res.locals.shopify.session);
  } catch (e) {
    // 如果产品创建失败，记录错误并设置错误状态
    console.log(`Failed to process products/create: ${e.message}`);
    status = 500;
    error = e.message;
  }
  
  // 返回操作结果
  res.status(status).send({ success: status === 200, error });
});

// GET /api/auth/info - 获取完整的授权信息用于API测试
app.get("/api/auth/info", async (_req, res) => {
  console.log('\n🔍 获取授权信息请求');
  console.log('=====================================');
  
  try {
    const session = res.locals.shopify?.session;
    
    if (!session) {
      console.log('❌ 未找到有效会话');
      return res.status(401).json({
        error: 'No valid session found',
        message: '请先完成OAuth授权',
        redirectUrl: '/api/auth?shop=YOUR_SHOP.myshopify.com'
      });
    }
    
    console.log('✅ 会话信息获取成功');
    console.log('- Shop:', session.shop);
    console.log('- Session ID:', session.id);
    console.log('- 访问令牌长度:', session.accessToken?.length || 0);
    
    // 构建完整的授权信息
    const authInfo = {
      // 基本信息
      shop: session.shop,
      sessionId: session.id,
      isOnline: session.isOnline,
      expires: session.expires,
      
      // 访问令牌信息
      accessToken: session.accessToken,
      scope: session.scope,
      
      // API配置信息
      apiVersion: process.env.SHOPIFY_API_VERSION,
      apiKey: process.env.SHOPIFY_API_KEY,
      hostName: process.env.HOST,
      
      // API端点信息
      endpoints: {
        restApiBase: `https://${session.shop}/admin/api/${process.env.SHOPIFY_API_VERSION}`,
        graphqlEndpoint: `https://${session.shop}/admin/api/${process.env.SHOPIFY_API_VERSION}/graphql.json`,
        webhookEndpoint: `https://${process.env.HOST}/api/webhooks`
      },
      
      // 示例API调用
      exampleRequests: {
        // REST API示例
        getProducts: {
          method: 'GET',
          url: `https://${session.shop}/admin/api/${process.env.SHOPIFY_API_VERSION}/products.json`,
          headers: {
            'X-Shopify-Access-Token': session.accessToken,
            'Content-Type': 'application/json'
          }
        },
        
        // GraphQL示例
        graphqlQuery: {
          method: 'POST',
          url: `https://${session.shop}/admin/api/${process.env.SHOPIFY_API_VERSION}/graphql.json`,
          headers: {
            'X-Shopify-Access-Token': session.accessToken,
            'Content-Type': 'application/json'
          },
          body: {
            query: `
              query {
                products(first: 10) {
                  edges {
                    node {
                      id
                      title
                      handle
                      createdAt
                    }
                  }
                }
              }
            `
          }
        },
        
        // 创建产品示例
        createProduct: {
          method: 'POST',
          url: `https://${session.shop}/admin/api/${process.env.SHOPIFY_API_VERSION}/products.json`,
          headers: {
            'X-Shopify-Access-Token': session.accessToken,
            'Content-Type': 'application/json'
          },
          body: {
            product: {
              title: "测试产品",
              body_html: "<strong>这是一个测试产品</strong>",
              vendor: "测试供应商",
              product_type: "测试类型",
              status: "draft"
            }
          }
        }
      },
      
      // 授权时间戳
      authTimestamp: new Date().toISOString(),
      
      // cURL示例
      curlExamples: {
        getProducts: `curl -X GET "https://${session.shop}/admin/api/${process.env.SHOPIFY_API_VERSION}/products.json" \\
  -H "X-Shopify-Access-Token: ${session.accessToken}" \\
  -H "Content-Type: application/json"`,
        
        graphqlQuery: `curl -X POST "https://${session.shop}/admin/api/${process.env.SHOPIFY_API_VERSION}/graphql.json" \\
  -H "X-Shopify-Access-Token: ${session.accessToken}" \\
  -H "Content-Type: application/json" \\
  -d '{"query":"query { shop { name } }"}'`,
        
        createProduct: `curl -X POST "https://${session.shop}/admin/api/${process.env.SHOPIFY_API_VERSION}/products.json" \\
  -H "X-Shopify-Access-Token: ${session.accessToken}" \\
  -H "Content-Type: application/json" \\
  -d '{"product":{"title":"测试产品","body_html":"测试描述"}}'`
      }
    };
    
    // 记录访问令牌信息（仅显示前几位）
    console.log('🎯 授权信息已准备完毕');
    console.log('- 访问令牌预览:', session.accessToken?.substring(0, 20) + '...');
    console.log('- 权限范围:', session.scope);
    console.log('- API版本:', process.env.SHOPIFY_API_VERSION);
    
    res.status(200).json(authInfo);
    
  } catch (error) {
    console.error('❌ 获取授权信息失败:', error);
    res.status(500).json({
      error: 'Failed to get auth info',
      message: error.message
    });
  }
});

// ===========================================
// 静态文件和前端应用配置
// ===========================================

// 应用CSP（内容安全策略）头部，增强安全性
app.use(shopify.cspHeaders());

// 配置静态文件服务，禁用目录索引
app.use(serveStatic(STATIC_PATH, { index: false }));

// 捕获所有路由，确保应用已安装在商店中，然后提供前端应用
app.use("/*", async (req, res, next) => {
  console.log('\n🌐 前端应用访问');
  console.log('=====================================');
  console.log('- 请求路径:', req.path);
  console.log('- Query参数:', JSON.stringify(req.query, null, 2));
  console.log('- Shop参数:', req.query.shop || '❌ 缺失');
  console.log('- Embedded参数:', req.query.embedded || '❌ 缺失');
  console.log('- Host参数:', req.query.host || '❌ 缺失');
  
  // 如果是嵌入式应用访问且缺少shop参数，尝试从其他地方获取
  if (!req.query.shop && req.query.host) {
    try {
      // 解码host参数获取shop信息
      const hostDecoded = Buffer.from(req.query.host, 'base64').toString();
      console.log('- 解码的Host:', hostDecoded);
      
      // 从host中提取shop信息
      const shopMatch = hostDecoded.match(/admin\.shopify\.com\/store\/(.+)/);
      if (shopMatch) {
        const shopDomain = shopMatch[1] + '.myshopify.com';
        console.log('- 从Host提取的Shop:', shopDomain);
        req.query.shop = shopDomain;
      }
    } catch (error) {
      console.log('- Host解码失败:', error.message);
    }
  }
  
  next();
}, shopify.ensureInstalledOnShop(), async (req, res, _next) => {
  console.log('\n✅ 应用已验证，提供前端应用');
  console.log('- 会话状态:', res.locals.shopify?.session ? '已验证' : '未验证');
  if (res.locals.shopify?.session) {
    console.log('- 商店:', res.locals.shopify.session.shop);
  }
  
  // 构建前端应用的查询参数
  const frontendUrl = new URL(req.url, `${req.protocol}://${req.get('host')}`);
  
  return res
    .status(200)
    .set("Content-Type", "text/html")
    .send(
      // 读取前端应用的index.html文件
      readFileSync(join(STATIC_PATH, "index.html"))
        .toString()
        // 将占位符替换为实际的Shopify API密钥
        .replace("%VITE_SHOPIFY_API_KEY%", process.env.SHOPIFY_API_KEY || "")
        // 添加shop和host参数到页面
        .replace(
          '</head>',
          `<script>
            window.shopifyConfig = {
              shop: "${req.query.shop || ''}",
              host: "${req.query.host || ''}",
              apiKey: "${process.env.SHOPIFY_API_KEY || ''}"
            };
          </script></head>`
        )
    );
});

// ===========================================
// 全局错误处理中间件
// ===========================================

app.use((err, req, res, next) => {
  console.log('\n💥 全局错误处理');
  console.log('=====================================');
  console.log('- 错误消息:', err.message);
  console.log('- 错误类型:', err.constructor.name);
  console.log('- 请求路径:', req.path);
  console.log('- 请求方法:', req.method);
  console.log('- 时间戳:', new Date().toISOString());
  
  if (err.stack) {
    console.log('- 错误堆栈:', err.stack);
  }
  
  // 根据错误类型返回适当的响应
  if (!res.headersSent) {
    if (err.message.includes('shop') || err.message.includes('session')) {
      // Shopify相关错误
      res.status(401).json({
        error: 'Authentication Error',
        message: err.message,
        type: err.constructor.name,
        timestamp: new Date().toISOString()
      });
    } else {
      // 通用服务器错误
      res.status(500).json({
        error: 'Internal Server Error',
        message: process.env.NODE_ENV === 'development' ? err.message : 'Something went wrong',
        timestamp: new Date().toISOString()
      });
    }
  }
});

// ===========================================
// 启动服务器
// ===========================================

// 在指定端口启动Express服务器
app.listen(PORT, () => {
  console.log('\n🎉 服务器启动成功!');
  console.log('=====================================');
  console.log('- 端口:', PORT);
  console.log('- 环境:', process.env.NODE_ENV || 'development');
  console.log('- 时间:', new Date().toISOString());
  console.log('- 本地地址: http://localhost:' + PORT);
  console.log('- 外部地址: https://' + process.env.HOST);
  console.log('\n🔗 快速测试链接:');
  console.log('- OAuth开始: https://' + process.env.HOST + '/api/auth?shop=YOUR_SHOP.myshopify.com');
  console.log('=====================================\n');
});
